<template>
	<view class="preview">
		<view v-for="(file, index) in courseFiles" :key="index" class="file-item"
			@click="previewFile(file.originalName)">
			<image class="file-icon" src="/static/FileIcon.png"></image>
			<text>{{file.displayName}}</text>
		</view>
		<view v-if="courseFiles.length==0" class="empty-state">
			<text>暂无课程资料</text>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import {
		apigetCourseFilesdetails,
		apiGetUrlFiles
	} from "../../api/apis";
	import {
		ref
	} from 'vue';

	const courseId = ref('');
	const courseFiles = ref([]);

	onLoad((options) => {
		console.log("路由参数:", options);
		courseId.value = options.courseId || '';
		getCourseFiles();
	});
	onPullDownRefresh(() => {
		getCourseFiles().then(
			() => {
				uni.stopPullDownRefresh();
			})
	})
	const getCourseFiles = async () => {
		try {
			const res = await apigetCourseFilesdetails({
				courseId: courseId.value,
				headers: {
					'Cache-Control': 'no-cache'
				}
			});
			console.log(res);

			if (res.code == 0) {
				// 处理文件名，去除 UUID
				if (res.data.url_file != null) {
					courseFiles.value = res.data.url_file.map(file => ({
						originalName: file,
						displayName: file.replace(
							/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}_/, '')
					}));
				}
			} else {
				courseFiles.value = [];
			}
			console.log()
		} catch (error) {
			console.error('获取文件列表出现错误:', error);
			// uni.showToast({
			// 	title: "获取文件列表失败，请稍后重试",
			// 	icon: 'none',
			// 	duration: 2000
			// });

		}
	};

	// 在script部分添加预览方法
	const previewFile = async (originalName) => {
		uni.showLoading();
		try {
			const res = await apiGetUrlFiles({
				courseId: courseId.value,
				fileName: originalName
			})
			console.log(res)

			if (res.code === 0) {
				// 处理视频预览
				const ext = originalName.split('.').pop().toLowerCase();
				const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
				const videoExrs = ['mp4', 'avi', 'mkv', 'mov'];
				const textExrs = [
					'txt', 'text', // 通用文本格式
					'html', 'css', 'js', 'json', 'xml', 'md', 'yaml', 'yml', 'ini', 'conf', 'log', // 代码和配置文件
					'sh', 'bat', 'ps1', // 脚本文件
					'py', 'java', 'c', 'cpp', 'cs', 'php', 'rb', // 编程语言文件
					'csv', 'tsv', 'sql', 'diff', 'patch' // 其他文本格式
				];
				console.log(res.data.url_img.length);
				if (res.data.url_img.length > 0) {
					//ppt world pdf =》转图片预览
					uni.navigateTo({
						url: `/pages/file-preview/file-preview?images=${encodeURIComponent(JSON.stringify(res.data.url_img))}`
					});
				} else {
					// 调用video标签预览
					if (videoExrs.includes(ext)) {
						uni.navigateTo({
							url: `/pages/video-preview/video-preview?videoUrl=${encodeURIComponent(res.data.url_file)}`
						});
					} else if (imageExts.includes(ext)) {
						// 图片预览
						uni.navigateTo({
							url: `/pages/file-preview/file-preview?images=${encodeURIComponent(JSON.stringify([res.data.url_file]))}`
						});
					} else if (textExrs.includes(ext)) {
						// 文本文件预览
						console.log("匹配到文本文件")
						uni.navigateTo({
							url: `/pages/file-preview/txt-file-preview?file=${encodeURIComponent(JSON.stringify([res.data.url_file]))}`,
						});
					} else {
						uni.downloadFile({
							url: res.data.url_file,
							success: (downloadResult) => {
								if (downloadResult.statusCode === 200) {
									uni.openDocument({
										filePath: downloadResult.tempFilePath
									})
								}
							}
						})
					}
				}

			}
		} catch (err) {
			uni.showToast({
				title: '课件未上传',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	}
</script>

<style lang="scss">
	.empty-state {
		text-align: center;
		padding: 40rpx;
		color: #666;
		font-size: 28rpx;
	}

	.preview {
		padding-top: calc(var(--status-bar-height, 44px) + 20rpx);
		padding: 0 16px;
		max-width: 600px;
		margin: 10px auto 0;
		display: flex;
		flex-direction: column;
		gap: 12px;
	}

	.file-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		width: 100%;
		padding: 16px;
		border: 1px solid #e0e0e0;
		border-radius: 12px;
		background-color: #fafafa;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		overflow: hidden;
		position: relative;
		transition: background-color 0.3s ease;

		&:hover {
			background-color: #f0f0f0;
		}
	}

	.file-icon {
		width: 48px;
		height: 48px;
		margin-right: 16px;
		flex-shrink: 0;
		object-fit: cover;
	}

	.file-item text {
		flex: 1;
		font-size: 16px;
		font-weight: 500;
		color: #222;
		line-height: 1.4;
		white-space: normal;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
	}
</style>